/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import NganLuongService.*;
import dao.ChiTietDonDatHangDAO;
import dao.DonDatHangDAO;
import dao.SanPhamDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import pojo.ChiTietDonDatHang;
import pojo.DonDatHang;
import pojo.SanPham;
import pojo.User;

/**
 *
 * @author User
 */
@WebServlet(name = "Cart", urlPatterns = {"/cart.do"})
public class Cart extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            ArrayList<SanPham> cart;
            HttpSession session = request.getSession();
            if (session.getAttribute("cart") == null) {

                cart = new ArrayList<SanPham>();
                session.setAttribute("cart", cart);
            } else {
                cart = (ArrayList<SanPham>) session.getAttribute("cart");
            }
            String action = request.getParameter("action");

            if (action != null) {

                String param_id = request.getParameter("id");
                int id;
                if (action.equals("add")) {
                    id = Integer.parseInt(param_id);
                    Boolean flag = false;
                    for (int i = 0; i < cart.size(); i++) {

                        SanPham sp = new SanPham();
                        sp = cart.get(i);
                        if (sp.getId() == id) {
                            sp.setSoLuong(sp.getSoLuong() + 1);
                            flag = true;
                            break;
                        }

                    }
                    if (flag == false) {
                        SanPhamDAO infoDao = new SanPhamDAO();
                        SanPham info = new SanPham();
                        info = infoDao.find(id);
                        info.setSoLuong(1);
                        cart.add(info);
                    }


                } else if (action.equals("delete")) {
                    id = Integer.parseInt(param_id);
                    for (int i = 0; i < cart.size(); i++) {

                        SanPham sp = new SanPham();
                        sp = cart.get(i);
                        if (sp.getId() == id) {

                            cart.remove(i);
                            break;
                        }

                    }
                }
                session.setAttribute("cart", cart);
                if (action.equals("process")) {
                    if (session.getAttribute("current_user") != null) {
                        User curentUser = (User) session.getAttribute("current_user");
                        String payment = request.getParameter("payment");
                        if (payment != null) {
                            DonDatHangDAO ddhDao = new DonDatHangDAO();
                            DonDatHang ddh = new DonDatHang();
                            ddh.setMaKhachHang(curentUser.getId());
                            ddh.setNgayDat(new Date());
                            ddh.setTinhTrang(1);
                            int total = 0;
                            for (int i = 0; i < cart.size(); i++) {

                                SanPham sp = new SanPham();
                                sp = cart.get(i);
                                total += sp.getSoLuong() * sp.getGiaBan();

                            }

                            ddh.setTongTien(total);
                            ddhDao.create(ddh);
                            for (int i = 0; i < cart.size(); i++) {

                                SanPham sp = new SanPham();
                                sp = cart.get(i);
                                int price = sp.getSoLuong() * sp.getGiaBan();
                                ChiTietDonDatHangDAO ctddhDao = new ChiTietDonDatHangDAO();
                                ChiTietDonDatHang ctddh = new ChiTietDonDatHang();
                                ctddh.setDonDatHang(ddh);
                                ctddh.setDonGia(price);
                                ctddh.setSanPhamId(sp.getId());
                                ctddh.setSoLuong(sp.getSoLuong());
                                ctddhDao.create(ctddh);

                            }
                            session.removeAttribute("cart");
                            int flag = -1;
                            try {
                                flag = payment(curentUser.getEmail().trim(), curentUser.getMatKhau().trim(), total);

                            } catch (Exception e) {
                            }
                            if (flag != 1) {
                                String page = "message.jsp";
                                request.setAttribute("message", "Thanh Toán thất bại :" + flag);
                                RequestDispatcher rdr = request.getRequestDispatcher(page);
                                rdr.forward(request, response);
                                return;

                            }
                            response.sendRedirect("payments.do");
                        }
                    } else {
                        response.sendRedirect("signin.do?action=view");
                    }
                    String capNhat = request.getParameter("update");
                    if (capNhat != null) {
                        String[] s = request.getParameterValues("qty");
                        for (int i = 0; i < cart.size(); i++) {
                            int soLuong = Integer.parseInt(s[i]);
                            cart.get(i).setSoLuong(soLuong);
                        }

                    }

                }
            }


            String view = "index.jsp";
            request.setAttribute("page", "Cart");
            RequestDispatcher rd = request.getRequestDispatcher(view);
            rd.forward(request, response);
        } finally {
            out.close();
        }
    }

    private static int payment(String email, String pass, int sotien) {
        NganLuongWebService_Service service = new NganLuongWebService_Service();
        NganLuongService.NganLuongWebService port = service.getNganLuongWebServicePort();
        return port.payment(email, pass, sotien);
        //return port.cong(1,3);
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
